package com.gec.controller;

import com.gec.domain.PageBean;
import com.gec.domain.PageParam;
import com.gec.domain.Room;
import com.gec.service.abst.RoomService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/Room")
public class RoomController extends BaseController {

    private final RoomService roomService;


    public RoomController(RoomService roomService) {
        this.roomService = roomService;
    }

    @RequestMapping("/viewList")
    public String viewList() {
        return "room/roomList";
    }

    //1种方法: ResponseBody 来下发字符串数据。
    //2种方法: 配置 SpringMVC Json 格式转换器。
    //       {转换器自动生成 json 格式数据}
    @RequestMapping(value = "/jsonList",
            produces = "text/html;charset=UTF-8"
    )
    @ResponseBody
    public String jsonList(HttpServletRequest req) {
        //{1}调用 getPageParam 方法解析 req 中参数,
        //   获取分页相关信息, 搜索关键字。
        PageParam param = PageParam.getPageParam(req);
        PageBean<Room> pBean = null;
        try {
            pBean = roomService.getRoomList(param);
            return pBean.toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            //{ps}你要新建一个方法到 PageBean
            return pBean.errorMsg();
        }
    }

    @RequestMapping("/viewAdd")
    public String viewAdd() {
        return "room/addRoom";
    }

    @RequestMapping(value = "/saveRoom",
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String saveRoom(HttpServletRequest req) {
        try {
            Room room = getBean(req, Room.class);
            roomService.saveRoom(room);
            return sendSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }


    @RequestMapping(value = "/delRoom",
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String delRoom(@RequestParam("id") String id) {
        Room room;
        try {
            room = roomService.getRoomById(id);
            roomService.delRoom(room.getId());
            return sendData(room.getRoomNo());
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }

    @RequestMapping(value = "/getRoom",
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getRoom(HttpServletRequest req) {
        String id = req.getParameter("id");
        Room room ;
        try {
            room = roomService.getRoomById(id);
            return sendData(room);
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }
}
